﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using fanfu.Common;
using fanfu.Business;
using fanfu.Model;
using System.IO;
using System.Configuration;

public partial class Article : BasePage
{
    //所有文章信息
    private DataTable __Article = new DataTable();

    #region 自定义
    /// <summary>
    /// 绑定查询后的数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindDataBySearch(Repeater rptDataList, int page)
    {
        #region 获取查询条件
        //获取查询条件
        string caption = this.searchCaption.Value.Trim();
        string startTime = this.searchStartCreateTime.Value.Trim();
        string endTime = this.searchEndCreateTime.Value.Trim();
        byte articleTag = byte.Parse(this.searchArticleTag.SelectedItem.Value);
        int channelId = int.Parse(this.searchChannel.SelectedItem.Value);
        int order = int.Parse(this.searchOrder.SelectedItem.Value);
        byte articleType = byte.Parse(this.searchArticleType.SelectedItem.Value);
        byte flag = byte.Parse(this.searchFlag.SelectedItem.Value);
        byte canComment = byte.Parse(this.searchCanComment.SelectedItem.Value);
        byte setTop = byte.Parse(this.searchSetTop.SelectedItem.Value);
        #endregion

        #region 创建查询SQL语句和查询条件参数

        //创建查询SQL语句和查询条件参数
        string sqlString = "SELECT * FROM Article WHERE 1=1 ";
        List<SqlParameter> paraList = new List<SqlParameter>();

        if (caption != "")
        {
            sqlString += "AND Caption like @Caption ";
            paraList.Add(new SqlParameter("@Caption", "%"+caption+"%"));
        }
        if (startTime != "")
        {
            sqlString += "AND CreateTime>=@StartCreateTime ";
            paraList.Add(new SqlParameter("@StartCreateTime", Convert.ToDateTime(startTime)));
        }
        if (endTime != "")
        {
            sqlString += "AND CreateTime<@EndCreateTime ";
            paraList.Add(new SqlParameter("@EndCreateTime", Convert.ToDateTime(endTime).AddDays(1)));
        }
        if (articleTag != 0)
        {
            sqlString += "AND ArticleTag=@ArticleTag ";
            paraList.Add(new SqlParameter("@ArticleTag", articleTag));
        }
        if (channelId != 0)
        {
            sqlString += "AND ChannelId=@ChannelId ";
            paraList.Add(new SqlParameter("@ChannelId", channelId));
        }
        if (articleType != 0)
        {
            sqlString += "AND ArticleType=@ArticleType ";
            paraList.Add(new SqlParameter("@ArticleType", articleType));
        }
        if (canComment != 0)
        {
            sqlString += "AND CanComment=@CanComment ";
            paraList.Add(new SqlParameter("@CanComment", canComment));
        }
        if (setTop != 0)
        {
            sqlString += "AND SetTop=@SetTop ";
            paraList.Add(new SqlParameter("@SetTop", setTop));
        }
        if (flag != 0)
        {
            sqlString += "AND Flag=@Flag ";
            paraList.Add(new SqlParameter("@Flag", flag));
        }
        switch (order)
        {
            case 0: sqlString += "ORDER BY CreateTime DESC"; break;
            case 1: sqlString += "ORDER BY BrowserCount DESC"; break;
            case 2: sqlString += "ORDER BY CommentCount DESC"; break;
            case 3: sqlString += "ORDER BY LastModifyTime DESC"; break;
        }
        #endregion

        //给数据列表赋值
        __Article = SqlHelper.GetDataTable(sqlString, paraList.ToArray());
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __Article.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__Article.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 绑定全部数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindAllData(Repeater rptDataList, int page)
    {
        //清理查询框数据,避免单击页码时产生错误条件
        this.searchCaption.Value = "";
        this.searchStartCreateTime.Value = "";
        this.searchEndCreateTime.Value = "";
        this.searchArticleTag.SelectedIndex = 0;
        this.searchChannel.SelectedIndex = 0;
        this.searchOrder.SelectedIndex = 0;
        this.searchArticleType.SelectedIndex = 0;
        this.searchFlag.SelectedIndex = 0;
        this.searchCanComment.SelectedIndex = 0;
        this.searchSetTop.SelectedIndex = 0;

        //给数据列表赋值
        __Article = new ArticleRule().GetAllArticleInfo();
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __Article.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__Article.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 清理控件状态
    /// </summary>
    private void ClearInputState()
    {
        this.editID.Value = "";            //清除编辑的ID
        this.editSmallImageSrc.Value = ""; //清除缩略图值  
        this.deleteID.Value = "";          //清除删除的ID
        this.editState.Value = "false";    //取消编辑状态
        RunJavascript("AddNew();", true); //JS清空控件值
    }

    /// <summary>
    /// 绑定频道列表到下拉列表
    /// </summary>
    private void BindChannelList(DropDownList channelList)
    {
        string selectString = "SELECT * FROM Channel";
        DataTable channel = SqlHelper.GetDataTable(selectString);
        if (channel.Rows.Count > 0)
        {
            channelList.DataSource = channel;
            channelList.DataTextField = "ChannelName";
            channelList.DataValueField = "ID";
            channelList.DataBind();
        }
        channelList.Items.Insert(0, new ListItem("全部频道", "0", true));
    }

    /// <summary>
    /// 绑定页面所有下拉列表
    /// </summary>
    private void BindPageAllDropDownList() 
    {
        //绑定文章状态
        EnumPlus.BindDesEnumToListControl(this.searchFlag, typeof(ArticleFlag));
        //绑定文章类型
        EnumPlus.BindDesEnumToListControl(this.searchArticleType, typeof(ArticleType));
        EnumPlus.BindDesEnumToListControl(this.drpArticleType, typeof(ArticleType));
        this.drpArticleType.Items.RemoveAt(0);
        //绑定文章排序
        EnumPlus.BindDesEnumToListControl(this.searchOrder, typeof(ArticleOrder));
        //绑定文章标签
        EnumPlus.BindDesEnumToListControl(this.searchArticleTag, typeof(ArticleTag));
        EnumPlus.BindDesEnumToListControl(this.drpArticleTag, typeof(ArticleTag));
        this.drpArticleTag.Items.RemoveAt(0);
        //绑定文章评论
        EnumPlus.BindDesEnumToListControl(this.searchCanComment, typeof(ArticleCanComment));
        //绑定文章置顶
        EnumPlus.BindDesEnumToListControl(this.searchSetTop, typeof(ArticleSetTop));
        //加载频道列表到下拉列表
        BindChannelList(this.searchChannel);
        BindChannelList(this.drpChannelName);
        this.drpChannelName.Items.RemoveAt(0);
    }

    #endregion

    #region 页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {   
            //绑定页面所有下拉列表
            BindPageAllDropDownList();
            //绑定列表并转到第一页
            BindAllData(this.rptDataList, 1);
        }
        else
        {
            string controlName = Request.Params.Get("__EVENTTARGET");
            string eventArgument = Request.Params.Get("__EVENTARGUMENT");
            //请求是否来自分页
            if (controlName == "pagecut" && eventArgument != "")
            {
                int current = Convert.ToInt32(eventArgument);
                //绑定列表并转到请求页
                BindDataBySearch(this.rptDataList, current);
            }
        }
    }
    #endregion

    #region 编辑事件
    protected void lbtnEdit_Click(object sender, EventArgs e)
    {
        //设置编辑状态,选项卡跳转
        this.editState.Value = "true";
        RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);

        string editID = this.editID.Value;
        if (!string.IsNullOrEmpty(editID))
        {
            ArticleModel article = new ArticleRule().GetArticleByID(editID);

            //绑定值到页面控件
            this.txtCaption.Value = article.Caption;
            this.txtSubCaption.Value=article.SubCaption;
            this.txtCreator.Value=article.Creator;
            this.drpArticleTag.ClearSelection();
            this.drpArticleTag.Items.FindByValue(article.ArticleTag.ToString()).Selected = true;
            this.drpChannelName.ClearSelection();
            this.drpChannelName.Items.FindByValue(article.ChannelId.ToString()).Selected = true;
            this.drpArticleType.ClearSelection();
            this.drpArticleType.Items.FindByValue(article.ArticleType.ToString()).Selected = true;
            this.txtSourceUrl.Value = article.SourceUrl;
            this.editor.Value = article.ArticleContent;
            this.chkCanComment.Checked = article.CanComment == (byte)ArticleCanComment.can ? true : false;
            this.chkSetTop.Checked = article.SetTop == (byte)ArticleSetTop.setTop ? true : false;
            this.chkFlag.Checked = article.Flag == (byte)ArticleFlag.normal ? true : false;
            this.logoimg.Src = article.LogoImg;
            this.editSmallImageSrc.Value = article.SmallLogoImg;
            this.txtKeywords.Value = article.Keywords;
            this.txtDes.Value = article.Des;
            this.txtTitle.Value = article.Title;
        }
    }
    #endregion

    #region 删除事件
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        int result = 0;
        string deleteItems = this.deleteID.Value;
        if (!string.IsNullOrEmpty(deleteItems))
        {
            string[] values = deleteItems.Split(',');
            foreach (string item in values)
            {
                result += new ArticleRule().DeleteArticle(item);
            }
            if (result == values.Length)
                RunJavascript("PopupMsg('success','恭喜您,删除成功！');", true);
            else
                RunJavascript("PopupMsg('error','错误,删除失败！');", true);
        }

        //绑定列表并转到第一页
        BindAllData(this.rptDataList, 1);
    }
    #endregion

    #region 保存事件
    protected void btnSave_Click(object sender, EventArgs e)
    {
        #region 获取控件值
        string caption = this.txtCaption.Value.Trim();
        string subCaption = this.txtSubCaption.Value.Trim();
        string creator = this.txtCreator.Value.Trim();
        if (creator == "")creator = CookieHelper.GetCookie("userAlias");
        byte articleTag = byte.Parse(this.drpArticleTag.SelectedItem.Value);
        int channelId = int.Parse(this.drpChannelName.SelectedItem.Value);
        string channelName = this.drpChannelName.SelectedItem.Text;
        byte articleType = byte.Parse(this.drpArticleType.SelectedItem.Value);
        string sourceUrl = this.txtSourceUrl.Value.Trim();
        string articleContent = this.editor.Value.Trim();
        byte canComment = this.chkCanComment.Checked == true ? (byte)ArticleCanComment.can : (byte)ArticleCanComment.cannot;
        byte setTop = this.chkSetTop.Checked == true ? (byte)ArticleSetTop.setTop : (byte)ArticleSetTop.notSetTop;
        byte flag = this.chkFlag.Checked == true ? (byte)ArticleFlag.normal : (byte)ArticleFlag.delete;
        string keywords = this.txtKeywords.Value.Trim();
        string des = this.txtDes.Value.Trim();
        string title = this.txtTitle.Value.Trim();
        string logoImg = string.Empty;
        string smallLogoImg = string.Empty; //缩略图

        //获取当前的logo图片地址
        string oldLogoImg = logoImg = this.logoimg.Src;
        string oldSmallLogoImg = smallLogoImg = this.editSmallImageSrc.Value;
        #endregion

        #region 上传文章Logo图片
        string fileUpName = this.fupLogoImg.FileName;
        try
        {
            if (fileUpName != "")
            {
                //配置文件没有设置时则设置默认路径
                string configPath = ConfigurationManager.AppSettings["ArticleLogoPath"];
                if (string.IsNullOrEmpty(configPath))
                    configPath = "~/Upload/ArticleLogo/";

                //物理路径不存在则创建物理路径
                string realityPath = Server.MapPath(configPath);
                if (!Directory.Exists(realityPath))
                    Directory.CreateDirectory(realityPath);

                FileInfo fileInfo = new FileInfo(fileUpName);
                string fileType = fileInfo.Extension.ToLower();
                bool isImageFile = ".gif".Equals(fileType) || ".jpg".Equals(fileType) || ".bmp".Equals(fileType) || ".png".Equals(fileType);
                if (isImageFile)
                {
                    fileUpName = articleTag +"-"+ DateTime.Now.ToString("yyyyMMddhhmmss") +"-"+ fileUpName;
                    logoImg = configPath + fileUpName;
                    this.fupLogoImg.SaveAs(realityPath + fileUpName);
                    //上传新Logo成功后删除原Logo
                    if (oldLogoImg != "")
                    {
                        //解除缓存或目录被删除导致的错误
                        try { File.Delete(Server.MapPath(oldLogoImg)); }
                        catch (Exception ex) { }
                    }

                    //创建并保存缩略图
                    smallLogoImg = CreateSmallImage(configPath, fileUpName, 150, 150);
                    //缩略图创建成功后删除原图
                    if (oldSmallLogoImg != "")
                    {
                        //解除缓存或目录被删除导致的错误
                        try { File.Delete(Server.MapPath(oldSmallLogoImg)); }
                        catch (Exception ex) { }
                    }
                }
                else
                {
                    RunJavascript("PopupMsg('error','上传文件类型错误,请选择.gif、.jpg、.bmp、.png格式的图片文件！');", true);
                    RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
                    return;
                }
            }
        }
        catch (Exception ex)
        {
            RunJavascript("PopupMsg('error','错误,文件上传失败！');", true);
            return;
        }
        #endregion

        //是否是修改状态
        if (this.editState.Value == "true")
        {
            string editID = this.editID.Value;
            #region 更新文章
            //更新文章
            string sqlString = "UPDATE Article SET Caption=@Caption, SubCaption=@SubCaption, Creator=@Creator," +
                " ArticleTag=@ArticleTag, ChannelId=@channelId, ChannelName=@ChannelName, ArticleType=@ArticleType, SourceUrl=@SourceUrl," +
                " ArticleContent=@ArticleContent, CanComment=@CanComment, SetTop=@SetTop, Flag=@Flag, Keywords=@Keywords," +
                " LastModifyPeople=@Creator,  LastModifyTime=@LastModifyTime, Des=@Des, Title=@Title, LogoImg=@LogoImg, SmallLogoImg=@SmallLogoImg WHERE ID=@ID";
            List<SqlParameter> paraList = new List<SqlParameter>();
            paraList.Add(new SqlParameter("@Caption", caption));
            paraList.Add(new SqlParameter("@SubCaption", subCaption));
            paraList.Add(new SqlParameter("@Creator", creator));
            paraList.Add(new SqlParameter("@ArticleTag", articleTag));
            paraList.Add(new SqlParameter("@ChannelId", channelId));
            paraList.Add(new SqlParameter("@ChannelName", channelName));
            paraList.Add(new SqlParameter("@ArticleType", articleType));
            paraList.Add(new SqlParameter("@SourceUrl", sourceUrl));
            paraList.Add(new SqlParameter("@ArticleContent", articleContent));
            paraList.Add(new SqlParameter("@CanComment", canComment));
            paraList.Add(new SqlParameter("@SetTop", setTop));
            paraList.Add(new SqlParameter("@Flag", flag));
            paraList.Add(new SqlParameter("@Keywords", keywords));
            paraList.Add(new SqlParameter("@LastModifyPeople", creator));
            paraList.Add(new SqlParameter("@LastModifyTime", DateTime.Now));
            paraList.Add(new SqlParameter("@Des", des));
            paraList.Add(new SqlParameter("@Title", title));
            paraList.Add(new SqlParameter("@LogoImg", logoImg));
            paraList.Add(new SqlParameter("@SmallLogoImg", smallLogoImg));
            paraList.Add(new SqlParameter("@ID", editID));

            int result = SqlHelper.ExecuteCommand(sqlString, paraList.ToArray());
            if (result == 1)
            {
                #region 手动级联更新
                //更新属于文章的评论
                string sqlUpdateReview = "UPDATE Review SET ParentName='" + caption + "' WHERE ParentId=" + editID + " AND ParentType=" + (int)ReviewParentType.article;
                SqlHelper.ExecuteCommand(sqlUpdateReview);
                #endregion
                RunJavascript("PopupMsg('success','恭喜您,更新成功！');", true);
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,更新失败！');", true);
                RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            }
            #endregion
        }
        else
        {
            #region 新增文章
            //新增文章
            ArticleModel article = new ArticleModel();
            article.Caption = caption;
            article.SubCaption = subCaption;
            article.Creator = creator;
            article.ArticleTag = articleTag;
            article.ChannelId = channelId;
            article.ChannelName = channelName;
            article.ArticleType = articleType;
            article.SourceUrl = sourceUrl;
            article.ArticleContent = articleContent;
            article.CanComment = canComment;
            article.SetTop = setTop;
            article.Flag = flag;
            article.Keywords = keywords;
            article.Des = des;
            article.Title = title;
            article.LogoImg = logoImg;
            article.SmallLogoImg = smallLogoImg;
            article.CreateTime = DateTime.Now;
            article.LastModifyTime = Convert.ToDateTime("1753-1-1");
            article.LastModifyPeople = "未被修改过";
            article.CommentCount = 0;
            article.BrowserCount = 0;

            int result = SqlHelper.ExecuteCommand(ArticleModel.GetInsertSQL(), article.ToSqlParameters());
            if (result == 1)
            {
                RunJavascript("PopupMsg('success','恭喜您,新建成功！');", true);
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,新建失败！');", true);
                RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            }
            #endregion
        }

        //绑定列表并转到第一页
        BindAllData(this.rptDataList, 1);
    }
    #endregion

    #region 查询事件
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //绑定列表并转到第一页
        BindDataBySearch(this.rptDataList, 1);
    }
    #endregion
}